import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { useUserStore } from '@/store/user';
import { getApiBaseURL } from '@/config/env';

const service: AxiosInstance = axios.create({
    baseURL: getApiBaseURL(),
    timeout: 10000
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 使用用户 Store 获取认证头
        const userStore = useUserStore();
        const authHeader = userStore.getAuthHeader();
        if (authHeader) {
            config.headers.Authorization = authHeader;
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    (error: AxiosError) => {
        console.log("response error ===>", error);
        
        // 处理 401 未授权错误
        if (error.response?.status === 401) {
            const userStore = useUserStore();
            userStore.clearUser();
            
            // 清除所有本地存储
            localStorage.clear();
            sessionStorage.clear();
            
            // 跳转到登录页面
            window.location.href = '/#/login';
        }
        
        return Promise.reject(error.response?.data || error);
    }
);

export default service;
